const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const moment = require('moment');
const SALT_ROUNDS = 10;

const userSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: false,
    },
    userName: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: false
    },
    phoneNumber: {
        type: String,
        required: false
    },
    gender: {
        type: String,
        required: false
    },
    departmentId: {
        type: String,
        ref: "department",
        required: false
    },
    post: {
        type: String,
        required: false
    },
    remark: {
        type: String,
        required: false
    },
    role: {
        type: String,
        required: false
    },
    state: {
        type: String,
        required: false
    },
    userNickname: {
        type: String,
        required: false
    },
}, {
    collection: 'user', timestamps: true, toJSON: {
        virtuals: true,
        transform: (doc, ret) => {
            ret.createdAt = moment(ret.createdAt).format('YYYY-MM-DD HH:mm:ss');
            ret.updatedAt = moment(ret.updatedAt).format('YYYY-MM-DD HH:mm:ss');
            delete ret.__v;
            id = ret._id;
            ret.deptName = ret.departmentId?.deptName;
            ret.deptId = ret.departmentId?.id;
            return ret;
        }
    },
    toObject: { virtuals: true }
});

userSchema.pre('save', function (next) {
    if (!this.isModified('password')) return next();
    bcrypt.hash(this.password, SALT_ROUNDS, (err, hash) => {
        if (err) return next(err);
        this.password = hash;
        next();
    });
});
// 新增pre('findOneAndUpdate')钩子
userSchema.pre('findOneAndUpdate', async function (next) {
    const update = this.getUpdate();
    if (update.password) {
        try {
            const hash = await bcrypt.hash(update.password, SALT_ROUNDS);
            this.setUpdate({ ...update, password: hash });
        } catch (err) {
            return next(err);
        }
    }
    next();
});
module.exports = mongoose.model('User', userSchema);